package com.lzy.chat.c_service;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.lzy.chat.a_entity.User;
import com.lzy.chat.c_service.Exception.Exceptions;
import com.lzy.chat.c_service.Exception.ServiceException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;

@Service
public class TokenService {
    public String getToken(User user) {
        Date start = new Date();
        Date end = new Date(start.getTime() + (long) 30 * 24 * 60 * 60 * 1000);//30天有效时间
        return JWT.create().withAudience(user.getId().toString()).withIssuedAt(start)
                .withExpiresAt(end).sign(Algorithm.HMAC256(user.getSalt()));
    }

    public int getUidFromToken(String token) {
        int uid;
        try {
            uid = Integer.parseInt(JWT.decode(token).getAudience().get(0));
        } catch (Exception e) {
            throw new ServiceException(Exceptions.TokenDecodeException, Arrays.toString(e.getStackTrace()));
        }
        return uid;
    }

    public boolean verifyToken(User user, String token) {
        try {
            int uid = getUidFromToken(token);
            if (uid != user.getId()) return false;
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getSalt())).build();
            jwtVerifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
